package com.xia.config;

import com.xia.utils.Const;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Set;

public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 定义那些路径不需要拦截
        // 登录页面 + 登录请求，注册页面 + 请求，
        Set<String> uri = new HashSet<>();
        uri.add("/toLogin");
        uri.add("/toRegister");
        uri.add("/realLogin");
        uri.add("/checkReader");
        uri.add("/readerRegister");

        // 获取请求的路径
        String contextPath = request.getServletPath();
        // 拦截其中定义了该请求，则不拦截
        if (uri.contains(contextPath)){
            return true;
        }

        // 判断session
        HttpSession session = request.getSession();
        Object admin = session.getAttribute(Const.ADMIN);
        Object reader = session.getAttribute(Const.READER);
        if (admin != null || reader != null){
            return true;
        } else {
            // 重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/toLogin");
            return false;
        }
    }
}
